Shared Access Signatures (1 / 7): You are developing a .NET application that interacts with Azure Blob Storage. You need to generate a token that will allow a client to have read and write access to a specific blob in your storage account for a period of 24 hours. This token should be generated in a secure manner without sharing your storage account key. The client is authenticated with Microsoft Entra ID. Write the C# code to accomplish this task.
// Define your storage account name, container name, and blob name
string accountName = "<storage-account-name>";
string containerName = "<container-name>";
string blobName = "<blob-name>";
Answer:
// Define your storage account name, container name, and blob name
string accountName = "<storage-account-name>";
string containerName = "<container-name>";
string blobName = "<blob-name>";
var credential = new DefaultAzureCredential();
var blobServiceClient = new BlobServiceClient(new Uri($"https://{accountName}.blob.core.windows.net", credential));
// Get a user delegation key for the Blob service that's valid for 24 hours
var delegationKey = await blobServiceClient.GetUserDelegationKey(DateTimeOffset.UtcNow, DateTimeOffset.UtcNow.AddDays(1));
var sasBuilder = new BlobSasBuilder()
{
BlobContainerName = containerName,
BlobName = blobName,
Resource = "b",
StartsOn = DateTimeOffset.UtcNow,
ExpiresOn = DateTimeOffset.UtcNow.AddDays(1),
Protocol = SasProtocol.Https
};
sasBuilder.SetPermissions(BlobSasPermissions.Read | BlobSasPermissions.Write);
// Use the key to get the SAS token
string sasToken = sasBuilder.ToSasQueryParameters(delegationKey, accountName).ToString();